package com.neusoft.awt.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.neusoft.awt.model.Goods;
import com.neusoft.awt.model.Orders;
import com.neusoft.awt.model.User;
import com.neusoft.awt.service.GoodsService;
import com.neusoft.awt.service.OrdersService;
import com.neusoft.awt.service.UserService;
import com.neusoft.awt.utils.*;

@RestController
@RequestMapping("/orders")
public class OrdersController {
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserService userService;

	/**
	 * 新增
	 */
	@PostMapping("/insert")
	@Transactional
	public Result<String> insert(@RequestBody Orders orders) {
		Integer goodsid = orders.getGoodsid();
		// 查询商品信息
		Goods goods = goodsService.selectByPrimaryKey(goodsid);
		// 查询买家信息
		User buyer = userService.selectByPrimaryKey(orders.getBuyerid());

		// 计算订单总金额
		BigDecimal totalPrice = goods.getPrice().multiply(new BigDecimal(orders.getNum()));

		orders.setTotalPrice(totalPrice);
		orders.setSellerid(goods.getUserid());
		orders.setCreateTime(new Date());
		orders.setStatus(0);

		BigDecimal money = buyer.getMoney();// 原有余额
		int rs = money.compareTo(totalPrice);// 比较余额和订单总额
		if (rs == -1) {
			return ResultGenerator.genFailResult("余额不足！交易失败！");
		}

		// 扣减个人余额
		BigDecimal nowMoney = money.subtract(totalPrice);// 现有余额
		// 更新个人余额
		buyer.setMoney(nowMoney);
		userService.updateByPrimaryKey(buyer);
		int res = ordersService.insert(orders);
		if(res<1){
			return ResultGenerator.genFailResult("交易失败！请重试！");
		}
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 删除
	 */
	@GetMapping("/delete/{ids}")
	public Result<String> delete(@PathVariable("ids") String ids) {
		if (null == ids || ids.equals("")) {
			return ResultGenerator.genFailResult(null);
		}
		String str[] = ids.split(",");
		for (String s : str) {
			ordersService.deleteByPrimaryKey(Integer.valueOf(s));
		}
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 更新
	 */
	@PostMapping("/update")
	public Result<String> update(@RequestBody Orders orders) {
		int res = ordersService.updateByPrimaryKey(orders);
		if (res == 1) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult(null);
		}
	}

	/**
	 * 主键查询
	 */
	@GetMapping("/info/{id}")
	public Result<?> selectById(@PathVariable("id") int id) {
		Orders orders = ordersService.selectByPrimaryKey(id);
		if (null == orders) {
			return ResultGenerator.genFailResult(null);
		} else {
			return ResultGenerator.genSuccessResult(orders);
		}
	}

	/**
	 * 条件和排序的分页查询
	 */
	@PostMapping("/search")
	public HashMap<String, Object> search(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, Orders orders, HttpServletResponse response) {
		// 设置分页参数
		Map<String, Object> map = new HashMap<String, Object>();
		if (page != null && rows != null) {
			PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}

		// 设置排序参数
		map.put("sort", "id");

		// 发送数据
		List<Orders> list = ordersService.select(map);
		int total = ordersService.count(map);
		HashMap<String, Object> result = new HashMap<>();
		result.put("rows", list);
		result.put("total", total);
		return result;
	}
	
	
	/**
	 * 根据buyerid查询订单
	 */
	@GetMapping("/selectByBuyerid/{buyerid}")
	public Result<?> selectByUserid(@PathVariable("buyerid")int buyerid){
		List<Orders> orders = ordersService.selectByUserid(buyerid);
		return ResultGenerator.genSuccessResult(orders);
	}
	
	/**
	 * 根据sellerid查询订单
	 */
	@GetMapping("/selectBySellerid/{sellerid}")
	public Result<?> selectBySellerid(@PathVariable("sellerid")int sellerid){
		List<Orders> orders = ordersService.selectBySellerid(sellerid);
		return ResultGenerator.genSuccessResult(orders);
	}
}